﻿<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WorkPort</title>
    <style>
        /*Report Style Start*/
        ul.tabs {
            margin: 0px;
            padding: 0px;
            list-style: none;
            font-size: 12px;
        }

            ul.tabs li {
                background: none;
                color: #222;
                display: inline-block;
                padding: 5px 10px;
                cursor: pointer;
            }

                ul.tabs li.current {
                    background: #ededed;
                    color: #222;
                }

        ul.tabsub {
            margin: 0px;
            padding: 0px;
            list-style: none;
            font-size: 12px;
        }

            ul.tabsub li {
                background: #7BD94C;
                color: #222;
                display: inline-block;
                padding: 5px 10px;
                cursor: pointer;
            }

                ul.tabsub li.current {
                    background: #CCCCCC;
                    color: #222;
                }

        .tab-content {
            display: none;
            background: #ededed;
            padding: 15px;
        }

        .tabsub-content {
            display: none;
            background: #ededed;
            padding: 15px;
        }

        .tab-content.current {
            display: inherit;
        }

        .tabsub-content.current {
            display: inherit;
        }

        span.k-datepicker, span.k-timepicker, span.k-datetimepicker, span.k-colorpicker, span.k-numerictextbox, span.k-combobox, span.k-dropdown {
            font-size: 12px;
        }
        /*Report Style End*/
    </style>
    <link rel="shortcut icon" href="../imgs/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" type="text/css" href="../lib/kendo/styles/kendo.common-bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../lib/kendo/styles/kendo.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
    <link rel="stylesheet" type="text/css" href="../css/layout.css">
    <script src="../lib/kendo/js/jquery.min.js"></script>
    <script src="../lib/kendo/js/kendo.all.min.js"></script>
    <script src="../lib/kendo/js/jquery.transit.min.js"></script>
    <script src="../lib/jquery.slimscroll.min.js"></script>
    <script src="../js/svs.framework.js"></script>
    <!--<script src="../js/wp.js"></script>-->
    <script src="../js/report.api.js"></script>
</head>

<body style="width:800px;">
    <!--Report HTML Start-->
    <div id="Report_window" class="wp_pl_15 wp_mr_15" style="width:800px;border: 1px solid #a59d9d; display: block">
        <div class="wp_mt_10 wp_mb_10 wp_ml_10 wp_mr_10">

            <label for="datepicker" class="wp_fz_12">Start Date: </label><input id="startdatepicker" value="" class="wp_w_87" maxlength=10 />
            <label for="datepicker" class="wp_fz_12">End Date: </label><input id="enddatepicker" value="" class="wp_w_87" maxlength=10 />
            <div style="float:right">
                <button id="filterDate" type="button" class="k-button" onclick="getReports(true)"> Filter </button>&nbsp;
                <button id="filterDate" type="button" class="k-button" onclick="getReports(false)"> Clear </button>
            </div>
        </div>
        <ul class="tabs">
            <li class="tab-link current wp_fz_12" id="tabm-1" onclick="toggleTab('1')">Pie Chart</li>
            <li class="tab-link wp_fz_12" id="tabm-2" onclick="toggleTab('2')">Bar Chart</li>
            <li class="tab-link wp_fz_12" id="tabm-3" onclick="toggleTab('3')">Stacked Bar</li>
        </ul>
        <div id="tab-1" class="tab-content current">
            <ul class="tabsub">
                <li class="tab-link current wp_fz_12" id="tabsm-1" onclick="toggleSubTab('1')">Total Visitors</li>
                <li class="tab-link wp_fz_12" id="tabsm-2" style="margin-left: 20px;" onclick="toggleSubTab('2')">Unique Visitors</li>
            </ul>
            <div id="tabs-1" class="tabsub-content current">
                <div id="pieTotalVisitChart"></div>
            </div>
            <div id="tabs-2" class="tabsub-content">
                <div id="pieUniqueVisitChart"></div>
            </div>
        </div>
        <div id="tab-2" class="tab-content">
            <div id="barChart" style="margin-top:35px"></div>
        </div>
        <div id="tab-3" class="tab-content">
            <div id="stackChart" style="margin-top:35px"></div>
        </div>

        <button id="excelReport" type="button" class="k-button wp_mt_10 wp_mr_10 wp_mb_10" style="width:100px;float:right" onclick="generateExcelReport()"> Generate Report </button>

    </div>
    <!--Report HTML End-->
    <!--Report Script Start-->
    <script type="text/javascript">
        var startDatePicker = '';
        var endDatePicker = '';
        var excelBarData = '';
        var excelTotalData = '';
        //Values to be excluded for Pie Chart Generation
        var toBeExcluded = [];
        toBeExcluded.push("WorkPort");


        $(document).ready(function () {
            //kendo date picker

            var startDate = $("#startdatepicker");
            var endDate = $("#enddatepicker")
            startDatePicker = startDate.kendoDatePicker({ format: "MM/dd/yyyy" }).data("kendoDatePicker");
            endDatePicker = endDate.kendoDatePicker({ format: "MM/dd/yyyy" }).data("kendoDatePicker");
            startDate.css("color", '#a6a6a6');
            endDate.css("color", '#a6a6a6');

            var today = new Date();
            var dd = today.getDate();
            var mm = mm1 = today.getMonth() + 1;
            var yyyy = today.getFullYear();

            if (dd < 10) {
                dd = '0' + dd
            }

            if (mm < 10) {
                mm = '0' + mm
            }

            today = mm + '/' + dd + '/' + yyyy;

            var oldDate = addMonths(new Date(), -3); // Three months before now
            var olddd = oldDate.getDate();
            var oldmm = oldDate.getMonth() + 1;
            var oldyyyy = oldDate.getFullYear();

            if (olddd < 10) {
                olddd = '0' + olddd
            }

            if (oldmm < 10) {
                oldmm = '0' + oldmm
            }
            oldDate = oldmm + '/' + olddd + '/' + oldyyyy;

            endDatePicker.value(today);
            startDatePicker.value(oldDate);

            getReports(true);
        });

        function addMonths(date, months) {
            date.setMonth(date.getMonth() + months);
            return date;
        }

        function toggleSubTab(obj) {
            $('ul.tabsub li').removeClass('current');
            $('.tabsub-content').removeClass('current');

            $(this).addClass('current');
            $("#tabs-" + obj).addClass('current');
            $("#tabsm-" + obj).addClass('current');
        }

        function toggleTab(obj) {
            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');

            $(this).addClass('current');
            $("#tab-" + obj).addClass('current');
            $("#tabm-" + obj).addClass('current');
        }

        function initChartsBarAndStack(flag) {
            var strStartDate = $("#startdatepicker").val();
            var strEndDate = $("#enddatepicker").val();
            //var isFetchDt =;
            $(".k-tabstrip .k-content .k-chart").empty().each(function () {
                $(this).removeClass(".k-chart").removeData();
            });

            Workport.ReportAPI.getReport(function (data) {
                var excelData = data;
                if (excelData.TotalVisits.length == 0 || excelData.UniqueVisits.length == 0 || excelData.Categories.length == 0) {
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = mm1 = today.getMonth() + 1;
                    var yyyy = today.getFullYear();

                    if (dd < 10) {
                        dd = '0' + dd
                    }

                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = mm + '/' + dd + '/' + yyyy;

                    var oldDate = addMonths(new Date(), -3); // Three months before now
                    var olddd = oldDate.getDate();
                    var oldmm = oldDate.getMonth() + 1;
                    var oldyyyy = oldDate.getFullYear();

                    if (olddd < 10) {
                        olddd = '0' + olddd
                    }

                    if (oldmm < 10) {
                        oldmm = '0' + oldmm
                    }
                    oldDate = oldmm + '/' + olddd + '/' + oldyyyy;
                    alert("No data is available for the selected date range. Please try with different date range");
                    //document.getElementById("barChart").innerHTML = "No data is available for the selected date range. Please try with different date range"
                    //chartView = false;
                    startDatePicker.value(oldDate);
                    endDatePicker.value(today);
                    
                }
                
                    $("#barChart").kendoChart({
                        title: {
                            text: "Visitors Stats"
                        },
                        legend: {
                            visible: true,
                            position: "right"
                        },
                        seriesDefaults: {
                            type: "column"
                        }, chartArea: {
                            height: 350

                        },
                        series: [{
                            name: "Total",
                            data: excelData.TotalVisits//[56000, 63000, 74000, 91000]
                        }, {
                            name: "Unique",
                            data: excelData.UniqueVisits//[52000, 34000, 23000, 48000]
                        }],
                        valueAxis: {
                            //max: 140000,
                            line: {
                                visible: false
                            },
                            minorGridLines: {
                                visible: true
                            }
                        },
                        categoryAxis: {
                            categories: excelData.Categories,//["GCalendar", "GDrive", "GMail", "WorkPort"],
                            majorGridLines: {
                                visible: false
                            }
                        },
                        tooltip: {
                            visible: true,
                            template: "#= series.name #: #= value #"
                        }
                    });

                    var duplicatiVisits = [];

                    for (var j = 0; j < excelData.UniqueVisits.length; j++) {
                        duplicatiVisits.push(excelData.TotalVisits[j] - excelData.UniqueVisits[j]);
                    }

                    $("#stackChart").kendoChart({
                        title: {
                            text: "Visitors Stats"
                        },
                        legend: {
                            visible: true,
                            position: "right"
                        },
                        seriesDefaults: {
                            type: "column",
                            stack: true
                        }, chartArea: {
                            height: 350

                        },
                        series: [{
                            name: "Unique",
                            data: excelData.UniqueVisits,
                            color: "#f3ac32"
                        }, {
                            name: "Duplicate",
                            data: duplicatiVisits,
                            color: "#b8b8b8"
                        }],
                        valueAxis: {
                            //max: 180,
                            line: {
                                visible: false
                            },
                            minorGridLines: {
                                visible: true
                            }
                        },
                        categoryAxis: {
                            categories: excelData.Categories,
                            majorGridLines: {
                                visible: false
                            }
                        },
                        tooltip: {
                            visible: true,
                            template: "#= series.name #: #= value #"
                        }
                    });

                
            }, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: flag, sync: true });


            //getJsonData(excelBarData);

            //Workport.ReportAPI.getTotalVisitReport(function (data) {
            //    excelTotalData = data;

            //}, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: flag, sync: true });

            //Workport.ReportAPI.getUniqueVisitReport(function (data) {
            //    excelUniqueData = data;

            //}, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: flag, sync: true });

        }

        function findAndRemove(array, property, value) {
            $.each(array, function (index, result) {
                if (result[property] == value) {
                    array.splice(index, 1);
                }
            });
        }

        function getReports(flag) {
            var today = new Date();
            var dd = today.getDate();
            var mm = mm1 = today.getMonth() + 1;
            var yyyy = today.getFullYear();

            if (dd < 10) {
                dd = '0' + dd
            }

            if (mm < 10) {
                mm = '0' + mm
            }

            today = mm + '/' + dd + '/' + yyyy;

            var oldDate = addMonths(new Date(), -3); // Three months before now
            var olddd = oldDate.getDate();
            var oldmm = oldDate.getMonth() + 1;
            var oldyyyy = oldDate.getFullYear();

            if (olddd < 10) {
                olddd = '0' + olddd
            }

            if (oldmm < 10) {
                oldmm = '0' + oldmm
            }
            oldDate = oldmm + '/' + olddd + '/' + oldyyyy;

            if (flag) {
                var strStartDate = $("#startdatepicker").val();
                var strEndDate = $("#enddatepicker").val();
                if (!strStartDate) {
                    alert("Start Date cannot be empty");
                }
                else if (!strEndDate) {
                    alert("End Date cannot be empty");
                }
                else if (Date.parse(strStartDate) > Date.parse(strEndDate)) {
                    alert("Invalid Date Range!\nStart date should be less than or equal to End date!");
                    startDatePicker.value(oldDate);
                    endDatePicker.value(today);
                    
                }
                else if (Date.parse(strEndDate) > Date.parse(today)) {
                    alert("End date cannot be greater than current date");
                    document.getElementById('enddatepicker').value = '';
                }
                else {
                    initChartsBarAndStack(flag);
                    initChartsPie(flag);
                }
            }
            else {

                endDatePicker.value(today);
                startDatePicker.value(oldDate);
                initChartsBarAndStack(flag);
                initChartsPie(flag);
            }
        }

        Date.daysBetween = function (date1, date2) {
            //Get 1 day in milliseconds
            var one_day = 1000 * 60 * 60 * 24;

            // Convert both dates to milliseconds
            var strdate1 = new Date(date1);
            var strdate2 = new Date(date2);

            var date1_ms = strdate1.getTime();
            var date2_ms = strdate2.getTime();

            // Calculate the difference in milliseconds
            var difference_ms = date2_ms - date1_ms;

            // Convert back to days and return
            return Math.round(difference_ms / one_day);
        }

        function generateExcelReport() {
            var excelSummary = '';
            var strStartDate = $("#startdatepicker").val();
            var strEndDate = $("#enddatepicker").val();

            //if (Date.daysBetween(strStartDate, strEndDate) <= 90) {
            //    Workport.ReportAPI.getExcelReport(function (data) {
            //        excelTotalData = data;
            //        JSONToCSVConvertor(excelTotalData, "Admin_Report", true, true);
            //    }, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: true, sync: true });
            //}
            //else {
                Workport.ReportAPI.getReport(function (data) {
                    excelSummary = data;
                    var reports = [];

                    for (var i = 0; i < excelSummary.Categories.length; i++) {
                        reports.push({
                            "App": excelSummary.Categories[i],
                            "Total Users": excelSummary.TotalVisits[i],
                            "Unique Users": excelSummary.UniqueVisits[i]
                        });
                    }

                    JSONToCSVConvertor(reports, "Admin_Report_Summary", true, false);
                }, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: false, sync: true });
            //}
        }

        function initChartsPie(flag) {

            var JsonDataTotalVisit = [];
            var JsonDataUniqueVisit = [];
            var strStartDate = $("#startdatepicker").val();
            var strEndDate = $("#enddatepicker").val();
            //var isFetchDt =;
            $(".k-tabstrip .k-content .k-chart").empty().each(function () {
                $(this).removeClass(".k-chart").removeData();
            });


            Workport.ReportAPI.getReport(function (dataSrc) {
                
                    if (toBeExcluded.length > 0) {
                        for (var x = 0 ; x < toBeExcluded.length; x++) {
                            var pos = dataSrc.Categories.indexOf(toBeExcluded[x]);
                            dataSrc.Categories.splice(pos, 1);
                            dataSrc.TotalVisits.splice(pos, 1);
                            dataSrc.UniqueVisits.splice(pos, 1);
                        }
                    }


                    var sumUniqueVisits = 0;
                    $.each(dataSrc.UniqueVisits, function () {
                        sumUniqueVisits += this;
                    });

                    var sumTotalVisits = 0;
                    $.each(dataSrc.TotalVisits, function () {
                        sumTotalVisits += this;
                    });

                    for (var j = 0; j < dataSrc.Categories.length; j++) {
                        JsonDataTotalVisit.push({
                            "AppName": dataSrc.Categories[j],
                            "Count": Math.round((dataSrc.TotalVisits[j] / sumTotalVisits) * 100)
                        });

                        JsonDataUniqueVisit.push({
                            "AppName": dataSrc.Categories[j],
                            "Count": Math.round((dataSrc.UniqueVisits[j] / sumUniqueVisits) * 100)
                        });
                    }

                //Pie Chart for Total Visit
                        $("#pieTotalVisitChart").kendoChart({

                            legend: {
                                visible: true,
                                position: "right"
                            },
                            chartArea: {
                                background: ""
                            },
                            dataSource: {
                                data: JsonDataTotalVisit
                            },
                            seriesDefaults: {
                                labels: {
                                    visible: true,
                                    background: "transparent",
                                    template: "#= category #: \n #= value#%"
                                }
                            }, chartArea: {
                                height: 350,
                                width: 740
                            },
                            series: [{
                                type: "pie",
                                startAngle: 150,
                                field: "Count",
                                categoryField: "AppName"
                            }],
                            seriesColors: ["#9de219", "#90cc38", "#068c35", "#004d38"],
                            tooltip: {
                                visible: true,
                                format: "{0}%"
                            }
                        });

                        //Pie Chart for Unique Visit
                        $("#pieUniqueVisitChart").kendoChart({

                            legend: {
                                visible: true,
                                position: "right"
                            },
                            chartArea: {
                                background: ""
                            },
                            dataSource: {
                                data: JsonDataUniqueVisit
                            },
                            seriesDefaults: {
                                labels: {
                                    visible: true,
                                    background: "transparent",
                                    template: "#= category #: \n #= value#%"
                                }
                            }, chartArea: {
                                height: 350,
                                width: 740
                            },
                            series: [{
                                type: "pie",
                                startAngle: 150,
                                field: "Count",
                                categoryField: "AppName"
                            }],
                            seriesColors: ["#9de219", "#90cc38", "#068c35", "#004d38"],
                            tooltip: {
                                visible: true,
                                format: "{0}%"
                            }
                        });
            }, { startDate: strStartDate, endDate: strEndDate, IsFetchWithDate: flag, sync: true });
        }

        function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, showDate) {
            //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

            var CSV = '';
            //Set Report title in first row or line

            CSV += ReportTitle + '\r\n\n';
            if (showDate) {
                CSV += "Start Date :- " + $("#startdatepicker").val() + "   End Date :- " + $("#enddatepicker").val() + '\r\n\n';
            }

            //This condition will generate the Label/Header
            if (ShowLabel) {
                var row = "";

                //This loop will extract the label from 1st index of on array
                for (var index in arrData[0]) {

                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }

                row = row.slice(0, -1);

                //append Label row with line break
                CSV += row + '\r\n';
            }

            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";

                //2nd loop will extract each column and convert it in string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }

                row.slice(0, row.length - 1);

                //add a line break after each row
                CSV += row + '\r\n';
            }

            if (CSV == '') {
                alert("Invalid data");
                return;
            }

            //Generate a file name
            var fileName = "";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g, "_");


            if (navigator.appName == 'Microsoft Internet Explorer' || navigator.userAgent.search("Trident") > 0) {
                //var IEwindow = window.open();
                ////IEwindow.document.write('sep=,\r\n' + CSV);
                ////IEwindow.document.close();
                //IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
                //IEwindow.close();
                var blob = new Blob([decodeURIComponent(encodeURI(CSV))], {
                    type: "text/csv;charset=utf-8;"
                });
                navigator.msSaveBlob(blob, fileName + ".csv");
            }
            else {
                //Initialize file format you want csv or xls
                var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

                // Now the little tricky part.
                // you can use either>> window.open(uri);
                // but this will not work in some browsers
                // or you will not get the correct file extension

                //this trick will generate a temp <a /> tag
                var link = document.createElement("a");
                link.href = uri;

                //set the visibility hidden so it will not effect on your web-layout
                link.style = "visibility:hidden";
                link.download = fileName + ".csv";

                //this part will append the anchor tag and remove it after automatic click
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }

    </script>
    <!--Report Script End-->
</body>


</html>